<!-- 库存管理 -->
<template>
  <div class="app-container">
    <el-form ref="form" inline :model="form" class="form-options" label-width="100px">
      <el-form-item label="器材分类">
        <el-select
          v-model="form.parentId"
          :remote-method="remoteEquipmentParent"
          filterable
          :loading="parentEquipmentLoading"
          @change="handleEquipmentParent"
          remote
          clearable>
          <!-- :key,必须是唯一的 -->
          <el-option
            v-for="item in equipmentParentOptions"
            :key="item.id"
            :label="item.parentName"
            :value="item.parentId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="器材名称">
        <el-select
          v-model="form.equipmentTypeId"
          :remote-method="remoteEquipment"
          filterable
          remote
          :loading="equipmentLoading"
          clearable>
          <el-option
            v-for="item in equipmentTypeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="仓库">
        <el-autocomplete
          ref="warehouseDisRef"
          v-model="form.warehouseDis"
          value-key="name"
          :fetch-suggestions="querySearchWarehouse"
          :trigger-on-focus="true"
          clearable
          @select="handleSelectWarehouse"
          @clear="clickClearwarehouseDisRef"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="form.status" filterable clearable>
          <el-option
            v-for="item in statusOptions"
            :key="item.id"
            :label="item.value"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生产日期" class="long-content">
        <el-date-picker
          v-model="form.productionDate"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="失效/报废日期" class="long-content">
        <el-date-picker
          v-model="form.expirationDate"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预警类型" style="width:405px;background:white;" v-if="false">
        <el-checkbox-group v-model="form.msgType" style="width:300px;">
          <el-checkbox style="width:65px;" label="1">库存预警</el-checkbox>
          <el-checkbox style="width:65px;" label="2">失效预警</el-checkbox>
          <el-checkbox style="width:65px;" label="3">未还预警</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <div class="btns">
        <el-button type="info" v-permission="['stock_manage_query']" @click="onReset('form')">重置</el-button>
        <el-button type="primary" v-permission="['stock_manage_query']" @click="onQuery">查询</el-button>
      </div>
    </el-form>
    <!-- 数据列表 -->
    <el-table
      :data="tableData"
      header-cell-class-name="table-header"
      style="width: 100%;margin-top: 20px">
      <el-table-column
        label="序号"
        type="index"
        width="50" align="center">
      </el-table-column>
      <el-table-column
        prop="parentName"
        label="器材分类" align="center">
      </el-table-column>
      <el-table-column
        prop="equipmentTypeName"
        label="器材名称" align="center">
      </el-table-column>
      <el-table-column prop="statusName" label="状态"></el-table-column>
      <el-table-column prop="stockAmount" label="总库存" align="center">
        <template slot-scope='scope'>
          <div style="text-align:center">
            <el-link @click="toDetail(scope.row,'stockAmount',scope.row.status)" type="primary" :underline="true"
                     style="color:blue;text-decoration:underline;">{{ scope.row.stockAmount }}
            </el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="stockAmountIn" label="在库库存" align="center">
        <template slot-scope='scope'>
          <div style="text-align:center">
            <el-link @click="toDetail(scope.row,'stockAmountIn')" type="primary" :underline="true"
                     style="color:blue;text-decoration:underline;">{{ scope.row.stockAmountIn }}
            </el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="stockAmountOut" label="在外库存" align="center">
        <template slot-scope='scope'>
          <div style="text-align:center">
            <el-link @click="toDetail(scope.row,'stockAmountOut')" type="primary" :underline="true"
                     style="color:blue;text-decoration:underline;">{{ scope.row.stockAmountOut }}
            </el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="equipmentTypeId" label="器材种类ID" v-if="false"></el-table-column>
      <el-table-column prop="status" label="库存状态" v-if="false"></el-table-column><!-- 状态(0正常1报废2失效),直接作为参数传递给明细页面 -->
    </el-table>
    <!-- 分页 -->
    <div style="text-align: right;margin-top: 15px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 15, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 库存明细（库存和在库库存） :visible.sync=""用来控制是否显示-->
    <el-dialog
      title="有效/在库库存明细"
      top="45px"
      v-if="stockDetailVisible"
      append-to-body
      :visible.sync="stockDetailVisible">
      <!-- 使用组件 通过组件属性传递参数给子组件parentEquipmentTypeId，'parentEquipmentTypeId'是设置的属性，调用方法时重新赋值了-->
      <!-- 父传子第二步：组件中定义属性-->
      <StockDetailComponent :parentEquipmentTypeId='parentEquipmentTypeId'
                            :parentWarehouseId='parentWarehouseId'></StockDetailComponent>

    </el-dialog>


    <!-- 库存明细（在外库存）-->
    <el-dialog
      title="在外库存明细"
      top="45px"
      v-if="stockDetailOutVisible"
      append-to-body
      :visible.sync="stockDetailOutVisible">
      <StockDetailOutComponent :parentEquipmentTypeId='parentEquipmentTypeId'
                               :parentWarehouseId='parentWarehouseId'></StockDetailOutComponent>
    </el-dialog>

    <!-- 库存明细（失效/报废）-->
    <el-dialog
      title="在外库存明细"
      top="45px"
      v-if="stockDetailScrapVisible"
      append-to-body
      :visible.sync="stockDetailScrapVisible">
      <StockDetailScrapComponent :parentEquipmentTypeId='parentEquipmentTypeId' :parentWarehouseId='parentWarehouseId'
                                 :parentStockStatus='parentStockStatus'></StockDetailScrapComponent>
    </el-dialog>

  </div>
</template>

<script>
import StockDetailComponent from '../components/StockDetailComponent'
import StockDetailOutComponent from '../components/StockDetailOutComponent'
import StockDetailScrapComponent from '../components/StockDetailScrapComponent'
import {
  getStockList,//库存列表
  getWarehouse,//仓库列表
  getBaseEquipmentTypeList//器材列表（非树形结构）
} from '@/api/warehouse'

export default {
  name: 'Stock',
  components: {
    //注册组件
    StockDetailComponent,
    StockDetailOutComponent,
    StockDetailScrapComponent
  },
  data() {
    return {
      currentPage: 1,
      total: 0,
      pageSize: 10,
      form: {
        parentId: '',
        parentDis: '',
        equipmentTypeId: '',
        equipmentTypeDis: '',
        warehouseId: '',
        warehouseDis: '',
        status: '',
        productionDateStart: '',
        productionDateEnd: '',
        expirationDateStart: '',
        expirationDateEnd: '',
        msgType: []
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      loading: false,
      equipmentLoading: false,
      parentEquipmentLoading: false,
      tableData: [],
      dialogVisible: false,

      //查询条件
      equipmentParentOptions: [],//器材分类
      equipmentTypeOptions: [],//器材名称
      warehouseOptions: [],//查询条件仓库
      statusOptions: [
        { 'value': '库存', 'id': '0' },
        { 'value': '报废', 'id': '1' },
        { 'value': '失效', 'id': '2' }
      ],//查询条件状态

      //子组件可见性
      stockDetailVisible: false,
      stockDetailOutVisible: false,
      stockDetailScrapVisible: false,
      //传给子组件
      parentEquipmentTypeId: '12345',//父传子第一步：定义变量
      parentWarehouseId: '',
      parentStockStatus: ''
    }
  },
  created() {

    getWarehouse({}).then(res => {
      this.warehouseOptions = res.resultData
      //验证打印
      //console.log("*************************"+this.warehouseOptions[5].name)
      //console.log("*************************"+this.warehouseOptions[5].id)
    })

    getBaseEquipmentTypeList({ equipmentTypeName: '' }).then(res => {
      this.equipmentTypeOptions = res.resultData
    })

    getBaseEquipmentTypeList({ parentName: '' }).then(res => {
      this.equipmentParentOptions = res.resultData
    })

    //调用查询获取数据，参数是默认参数
    this.onQuery()
  },
  methods: {
    onReset(searchForm) {
      // this.$refs[searchForm].resetFields();
      // console.log("重置");
      this.form = {
        parentId: '',
        parentDis: '',
        equipmentTypeId: '',
        equipmentTypeDis: '',
        warehouseId: '',
        warehouseDis: '',
        status: '',
        productionDateStart: '',
        productionDateEnd: '',
        expirationDateStart: '',
        expirationDateEnd: '',
        msgType: []
      }
    },
    onQuery() {
      this.currentPage = 1
      this.getTableData()
    },
    getTableData() {

      //生产日期
      if (this.form.productionDate && this.form.productionDate[0]) {
        this.form.productionDateStart = this.form.productionDate[0]
      } else {
        this.form.productionDateStart = ''
      }
      if (this.form.productionDate && this.form.productionDate[1]) {
        this.form.productionDateEnd = this.form.productionDate[1]
      } else {
        this.form.productionDateEnd = ''
      }
      //失效/报废日期
      if (this.form.expirationDate && this.form.expirationDate[0]) {
        this.form.expirationDateStart = this.form.expirationDate[0]
      } else {
        this.form.expirationDateStart = ''
      }
      if (this.form.expirationDate && this.form.expirationDate[1]) {
        this.form.expirationDateEnd = this.form.expirationDate[1]
      } else {
        this.form.expirationDateEnd = ''
      }

      const param = { page: this.currentPage, rows: this.pageSize }
      Object.assign(param, this.form)
      //console.log("提交的查询条件"+ JSON.stringify(param));
      getStockList(param).then(res => {
        this.tableData = res.resultData
        this.total = res.total
      })
    },

    //点击链接查看明细
    toDetail(row, type, st) {
      //console.log("warehouseId:"+this.form.warehouseId);
      //父传子第三步：变量赋值
      this.parentEquipmentTypeId = row.equipmentTypeId //属性重新赋值，传递给子组件
      this.parentWarehouseId = this.form.warehouseId
      //console.log("parentWarehouseId:"+this.parentWarehouseId);
      if (type == 'stockAmount') {
        if (st == '0') {//库存
          // console.log('库存明细-stockAmount')
          this.stockDetailVisible = true
        } else {//报废/失效
          // console.log('库存明细-stockAmountScrap')
          this.parentStockStatus = row.status
          this.stockDetailScrapVisible = true
        }
      } else if (type == 'stockAmountIn') {//跟有效库存是同一个，后台传递的参数不同
        // console.log('库存明细-stockAmountIn')
        this.stockDetailVisible = true
      } else if (type == 'stockAmountOut') {
        // console.log('库存明细-stockAmountOut')
        this.stockDetailOutVisible = true
      }
    },

    //--------------------分割--------------------查询条件模糊检索
    //过滤(方法共用)(内容全部加载的情况下使用，实时到数据库模糊查询的不需要这个筛选)
    createFilter(queryString) {
      return (rr) => {//rr列表中的元素，这个列表都会被筛选
        return (rr.name.toLowerCase().indexOf(queryString.toLowerCase()) != -1)
      }
    },

    /* 器材分类 */
    remoteEquipmentParent(query) {
      this.parentEquipmentLoading = true //加载过程中没有返回时转圈圈，显示加载中的状态；
      getBaseEquipmentTypeList({ parentName: query}).then(res => {
        this.equipmentParentOptions = res.resultData
        this.parentEquipmentLoading = false
      })
    },
    // 器材分类选择后器材名称联动，范围缩小
    handleEquipmentParent(){
      this.remoteEquipment('')
    },

    /* 器材名称 */
    remoteEquipment(query) {
      this.equipmentLoading = true
      //console.log("查询器材名称传递的参数信息，父级ID："+this.form.parentId+"模糊关键字："+query)
      getBaseEquipmentTypeList({ parentId: this.form.parentId, equipmentTypeName: query }).then(res => {
        this.equipmentTypeOptions = res.resultData
        this.equipmentLoading = false
      })
    },

    /* 仓库 */
    querySearchWarehouse: function(queryString, cb) {
      const results = this.warehouseOptions
      var rs = queryString ? results.filter(this.createFilter(queryString)) : results
      cb(rs)
    },
    handleSelectWarehouse(item) {
      this.form.warehouseId = item.id
    },
    clickClearwarehouseDisRef(){
      this.$nextTick(() => {
        if (this.$refs.warehouseDisRef) {
          this.$refs.warehouseDisRef.activated = true;
        }
      });
    },
    /* 状态 */
    querySearchStatus: function(queryString, cb) {
      const results = this.statusOptions
      var rs = queryString ? results.filter(this.createFilter(queryString)) : results
      cb(rs)
    },
    handleSelectStatus(item) {
      this.form.status = item.id
    },

    //分页用的方法
    handleSizeChange: function(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getTableData()
    },
    handleCurrentChange: function(val) {
      this.currentPage = val
      this.getTableData()
    }

  }
}
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}
</style>

